<template>  
  <el-form :inline="true" :model="ruleForm" class="demo-form-inline">  
    <el-form-item label="往来单位：">  
      <el-select v-model="ruleForm.organId" clearable style="width: 280px; margin-left: 10px;" placeholder="请选择往来单位">  
        <el-option v-for="customer in customers" :key="customer.id"  
          :label="`${customer.supName} ${customer.supType === '0' ? '[供应商]' : '[客户]'}`" :value="customer.supId" />  
      </el-select>  
    </el-form-item>  
    
    <el-form-item label="单据编号">  
      <el-input v-model="ruleForm.number" placeholder="自动生成单据编号" readonly></el-input>  
    </el-form-item>  
    
    <el-form-item label="创建时间">  
      <el-date-picker type="datetime" placeholder="选择日期与时间" clearable class="input" />  
    </el-form-item>  

    <el-form-item>  
      <el-button type="primary" @click="submitForm">保存</el-button>  
    </el-form-item>  

    <el-form-item label="财务人员：">  
      <el-select v-model="ruleForm.handsPersonId" clearable style="width: 200px; margin-left: 10px;"  
        placeholder="请选择财务人员">  
        <el-option v-for="persons in person" :key="persons.perId" :label="persons.perName" :value="persons.perId" />  
        <el-option :value="undefined" disabled style="cursor: pointer">  
          <el-button type="text" v-perm:finance:revenue:insert:financestaff="insert">  
            <i class="el-icon-menu"></i>新增财务人员  
          </el-button>  
        </el-option>  
      </el-select>  
    </el-form-item>  
    <div class="ant-col" style="margin-right: 10px;">
          <el-button type="primary" @click="addRow" class="ant-btn ant-btn-primary">
            <el-icon class="el-icon-left">
              <Plus />
            </el-icon>
            <span>插入行</span>
          </el-button>

        </div>
    <el-table :data="tableData" show-summary style="width: 100%">  
      <el-table-column label="收入项目" width="400">  
        <template #default="{ row }">  
          <el-select v-model="row.xm" clearable style="width: 293px; margin-left: 10px;"  
            placeholder="请选择收入项目">  
            <el-option v-for="status in stausData" :key="status.name" :label="status.name"  
              :value="status.id" />  
          </el-select>  
        </template>  
      </el-table-column>  
      <el-table-column label="金额" width="400">  
        <template #default="{ row }">  
          <el-input v-model="row.je"></el-input>  
        </template>  
      </el-table-column>  
      <el-table-column label="备注" width="400">  
        <template #default="{ row }">  
          <el-input v-model="row.bz"></el-input>  
        </template>  
      </el-table-column>  
    </el-table>  

    <div class="index-body zb">  
      <el-form-item label="结算账户：" style="margin-right: 120px;">  
        <el-select clearable style="width: 200px;" placeholder="请选择账户" v-model="ruleForm.accountId">  
          <el-option v-for="account in accounts" :key="account.id" :label="account.name" :value="account.accId" />  
        </el-select>  
      </el-form-item>  
      
      <el-form-item label="收取定金：" style="margin-right: 100px;">  
        <el-input style="width: 240px"></el-input>  
      </el-form-item>  
    </div>  

    <div class="ant-coloery" style="margin-right: 10px;">  
      <el-form-item label="附件：">  
        <el-button plain>  
          <el-icon style="margin-right: 10px;">  
            <MessageBox />  
          </el-icon>上传附件  
        </el-button>  
      </el-form-item>  
    </div>  
  </el-form>  

  <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="40%"  
    style="margin-left: 550px; margin-top: 200px">  
    <router-view @close="close" :data="data" @proty="proty"></router-view>  
  </el-dialog>  
</template>  

<script lang="ts" setup>  
import { reactive, ref, onMounted } from 'vue';  
import router from '@/router';  
import request from '@/api/request';  
import { ElMessage } from 'element-plus';  

const visible = ref(false);  
const title = ref("");  
const data = ref({});  
const ruleForm = ref({  
  linkNumber: '',  
  number: '',  
  organId: '',  
  accountId: '',  
  handsPersonId: '',  
});  

// Close dialog function  
const close = () => {  
  visible.value = false;  
};  

// Table data initialization  
const tableData = ref([{ barCode: '', categoryName: '', color: '' }]);  

// Add a new row to the table  
const addRow = () => {  
  tableData.value.push({  
    barCode: '',  
    categoryName: '',  
    color: '',  
  });  
};  

// Load accounts from the API  
const accounts = ref([]);  
const loadAccounts = () => {  
  request({ url: '/basic/account/list', method: 'get' })  
    .then(res => accounts.value = res.data)  
    .catch(err => console.error(err));  
};  
loadAccounts();  

// Submit form  
const submitForm = () => {  
  const totalAmount = tableData.value.reduce((sum, row) => sum + (parseFloat(row.je) || 0), 0);  

  const data = {  
    erpAccountHead: {  
      type:'收入',
      billNo: ruleForm.value.number,  
      organId: ruleForm.value.organId,  
      creator: '1',  
      accountId: ruleForm.value.accountId,  
      handsPersonId: ruleForm.value.handsPersonId,  
      changeAmount: totalAmount,  
      totalPrice: totalAmount,  
      status: '0',  
    },  
    erpAccountItems: tableData.value.map(row => ({  
      inOutItemId: row.xm,  
      remark: row.bz || '',  
      eachAmount: row.je,  
    })),  
  };  

  request({  
    url: '/accountHead/insertFind',  
    method: 'post',  
    data: data,  
    headers: { 'Content-Type': 'application/json' },  
  }).then(res => {  
    console.log(res);  
    ElMessage.success('提交成功');  
  }).catch(err => {  
    console.error(err);  
    ElMessage.error('提交失败: ' + (err.message || '请稍后重试'));  
  });  
};  

// Other functions...  
const stausData = [  
  { id: '1', name: '利息收入' },  
  { id: '2', name: '房租收入' }  
];  

let save = ref([]);  

const proty = (item) => {  
  console.log("proty被调用", item.number);  
  ruleForm.value.linkNumber = item.number;  
}  

const customers = ref([]); // 存储客户数据  

const loadCustomers = () => {  
  request({ url: '/basic/vendor/findBy', method: 'get' })  
    .then(res => {  
      console.log(res);  
      customers.value = res.data; // 更新客户数据  
    }).catch(err => {  
      console.error(err);  
    });  
};  
loadCustomers();  

const person = ref({});  
const personfin = () => {  
  request({ url: '/basic/person/list', method: 'get' })  
    .then(res => {  
      person.value = res.data;  
      console.log(res);  
    });  
}  
personfin();  

const insert = (p) => {  
  title.value = p.cname;  
  visible.value = true;  
  router.push(p.path);  
  personfin();  
};  

// 页面加载时生成订单编号  
onMounted(() => {  
  let currentOrderNumber = parseInt(localStorage.getItem('orderNumber') || '1', 10);  
  currentOrderNumber++;  
  const formattedOrderNumber = currentOrderNumber.toString().padStart(10, '0');  
  ruleForm.value.number = formattedOrderNumber;  
  localStorage.setItem('orderNumber', currentOrderNumber.toString());  
});  
</script>  

<style>  
.demo-form-inline .el-input {  
  --el-input-width: 220px;  
}  

.demo-form-inline .el-select {  
  --el-select-width: 220px;  
}  
</style>